<template>
  <div class="home-container">
    <!-- 头部区域 -->
    <van-nav-bar title="" left-text="返回" fixed left-arrow>
      <!-- 右侧的插槽 -->
      <template #right>
        <van-icon
          name="search"
          color="white"
          size="18"
          @click="$router.push('/search')"
        />
      </template>
      <!-- 左侧的插槽 -->
      <template #left>
        <img src="../../assets/toutiao_logo.png" alt="" class="logo" />
      </template>
    </van-nav-bar>
    <!-- 频道列表区域 -->
    <van-tabs
      v-model="active"
      sticky
      offset-top="1.22667rem"
      :before-change="beforeTabsChange"
      @change="onTabsChange"
    >
      <van-tab :title="item.name" v-for="item in channels" :key="item.id">
        <!-- //文章的列表组件 -->
        <ArtList :channelId="item.id" />
      </van-tab>
    </van-tabs>

    <!-- popup弹出层区域 -->
    <van-popup
      v-model="show"
      :close-on-click-overlay="false"
      @closed="isDel = false"
      ><div class="popup-container">
        <!-- 弹出层的头部区域 -->
        <van-nav-bar title="频道管理">
          <template #right>
            <van-icon
              name="cross"
              size="14"
              color="white"
              @click="show = false"
            />
          </template>
        </van-nav-bar>

        <!-- 弹出层的主体区域 -->
        <div class="pop-body">
          <!-- 我的频道 -->
          <div class="my-channel-box">
            <div class="channel-title">
              <div>
                <span class="title-bold">已添加频道：</span>
                <span class="title-gray">{{
                  isDel ? "点击移除频道" : "点击进入频道"
                }}</span>
              </div>
              <span class="btn-edit" @click="isDel = !isDel">
                {{ isDel ? "完成" : "编辑" }}</span
              >
            </div>
            <!-- 我的频道列表 -->
            <van-row type="flex">
              <van-col
                span="6"
                v-for="(item, index) in channels"
                :key="item.id"
              >
                <!-- 用户的频道 Item 项 -->
                <div
                  class="channel-item van-hairline--surround"
                  @click="onUserChannel(item, index)"
                >
                  {{ item.name }}
                  <!-- //删除的图表 -->
                  <van-badge
                    color="transparent"
                    class="cross-badge"
                    v-if="isDel && item.name !== '推荐' && channels.length > 2"
                  >
                    <template #content>
                      <van-icon
                        name="cross"
                        class="badge-icon"
                        color="#cfcfcf"
                        size="12"
                      />
                    </template>
                  </van-badge>
                </div>
              </van-col>
            </van-row>
          </div>

          <!-- 分隔线 -->
          <div class="van-hairline--top sp-line"></div>

          <!-- 更多频道 -->
          <div class="more-channel-box">
            <div class="channel-title">
              <div>
                <span class="title-bold">可添加频道：</span>
                <span class="title-gray">点击添加频道</span>
              </div>
            </div>
            <!-- 更多频道列表 -->
            <van-row type="flex">
              <van-col span="6" v-for="item in moreChannels" :key="item.id">
                <div
                  class="channel-item van-hairline--surround"
                  @click="addTochannel(item)"
                >
                  {{ item.name }}
                </div>
              </van-col>
            </van-row>
          </div>
        </div>
      </div>
    </van-popup>
    <van-icon name="plus" size="16" class="plus" @click="show = true" />
  </div>
</template>

<script>
// 导入需要的API接口
import { getUserChaneelsAPI, allChannelsAPI, updateUserChannelAPI } from '../../api/homeAPI'

// 导入列表组件
import ArtList from '../../components/ArtLIST/ArtList.vue'
// “频道名称”和“滚动条位置”之间的对应关系，格式 { '推荐': 211, 'html': 30, '开发者资讯': 890 }
const nameToTop = {}
export default {
  computed: {
    // 动态计算出未关注的频道列表数据
    moreChannels () {
      const newArr = []
      // 1. 循环全部频道
      // 2. 判断是否在 channels 数组中
      // 3. 如果不在，则添加到新数组中
      // 4. return 结果
      this.allChannels.forEach(item => {
        const r = this.channels.every(x => x.id !== item.id)
        if (r) {
          newArr.push(item)
        }
      })
      return newArr
    }
  },
  // 导航离开该组件的对应路由时调用
  // 可以访问组件实例 `this`
  beforeRouteLeave (to, from, next) {
    from.meta.top = window.scrollY
    next()
  },
  components: { ArtList },
  name: 'Home',
  data () {
    return {
      active: 0,
      channels: [],
      show: false, // 控制popup的显示隐藏
      allChannels: [],
      isDel: false

    }
  },
  created () {
    this.initUserChaneels()
    this.inintAllChannel()
  },
  methods: {
    // 当 tabs 切换完毕之后，触发此方法
    onTabsChange () {
      // 等 DOM 更新完毕之后，根据记录的"滚动条位置"，调用 window.scrollTo() 方法进行滚动
      this.$nextTick(() => {
        const name = this.channels[this.active].name
        window.scrollTo(0, nameToTop[name] || 0)
      })
    },
    // tabs 发生切换之前，触发此方法
    beforeTabsChange () {
      // 把当前"频道名称"对应的"滚动条位置"记录到 nameToTop 对象中
      const name = this.channels[this.active].name
      nameToTop[name] = window.scrollY

      // return true 表示允许进行标签页的切换
      return true
    },
    // 初始化用户的频道列表
    async initUserChaneels () {
      // 调用接口
      const { data: res } = await getUserChaneelsAPI()
      console.log(res)
      if (res.message === 'OK') { // 判断请求是否成功
        this.channels = res.data.channels// 把获取到的数据存储赋值给创建的列表数组
      }
    },
    async inintAllChannel () {
      const { data: res } = await allChannelsAPI()
      if (res.message === 'OK') {
        this.allChannels = res.data.channels
        console.log(this.allChannels)
      }
    },
    async updataChannel () {
      // 准备参数
      const newArr = this.channels.map((item, i) => {
        return {
          id: item.id,
          seq: i
        }
      })

      // 调用接口
      const { data: res } = await updateUserChannelAPI(newArr)

      if (res.message === 'OK') {
        // 提示信息
        this.$notify({ type: 'warning', message: '更新频道成功' })
      }
    },
    async addTochannel (item) {
      // 点击未关注的频道，添加到以关注的频道
      this.channels.push(item)
      this.updataChannel()
    },
    onUserChannel (item, index) {
      if (this.isDel) {
        if (this.channels.name === '推荐') return

        if (this.channels.name === '推荐' || this.channels.length === 2) return

        // 删除状态 点击删除
        this.channels = this.channels.filter(x => x.id !== item.id)
        this.updataChannel()
      } else {
        // 进入状态 进入频道
        this.active = index
        this.show = false
      }
    }
  }

}

</script>

<style lang="less" scoped>
img {
  width: 30%;
}
.home-container {
  padding-top: 46px;
  padding-bottom: 50px;
}
// 频道管理小图标的定位
.plus {
  position: fixed;
  top: 58px;
  right: 10px;
  z-index: 999;
}
/deep/ .van-tabs__wrap {
  padding-right: 36px;
  background-color: white;
}
.van-popup,
.popup-container {
  background-color: transparent;
  height: 100%;
  width: 100%;
}

.popup-container {
  display: flex;
  flex-direction: column;
}

.pop-body {
  flex: 1;
  overflow: scroll;
  padding: 8px;
  background-color: white;
}

.my-channel-box,
.more-channel-box {
  .channel-title {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    line-height: 28px;
    padding: 0 6px;
    .title-bold {
      font-weight: bold;
    }
    .title-gray {
      color: gray;
      font-size: 12px;
    }
  }
}

.btn-edit {
  border: 1px solid #a3a2a2;
  padding: 0 10px;
  line-height: 20px;
  height: 20px;
  border-radius: 6px;
  font-size: 12px;
}

.channel-item {
  font-size: 12px;
  text-align: center;
  line-height: 36px;
  background-color: #fafafa;
  margin: 6px;
}

.cross-badge {
  position: absolute;
  right: -3px;
  top: 0;
  border: none;
}

.sp-line {
  margin: 10px 0 20px 0;
}
</style>
